<template>
  <el-dialog
    :title="title"
    @close="cancel"
    :visible.sync="dialogVisible"
    width="50%">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="店铺名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入店铺名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="门店所属地区" prop="city">
            <el-cascader
              v-model="form.areaCity"
              clearable
              :options="citydata"
              :props="{
            expandTrigger: 'hover',
            children: 'children',
            label: 'name',
            value: 'id',
            checkStrictly:'true'
           }"
              :show-all-levels="true"
            ></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="归属地址：" prop="address">
        <el-autocomplete
          style="width: 100%"
          v-model="form.address"
          :fetch-suggestions="querySearchAsync"
          :trigger-on-focus="false"
          placeholder="请先搜索地址"
          clearable
          @select="handleSelect"
        >
          <template slot-scope="{ item }">
            <div style="overflow: hidden">
              <i class="el-icon-search fl mgr10"/>
              <div class="title">{{ item.title }}</div>
              <div class="address ellipsis">{{ item.address }}</div>
            </div>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="地图定位：" v-show="mapflag">
        <div ref="map-container" style="width: 100%; height: 300px"/>
      </el-form-item>
      <el-form-item label="经度：">
        <el-input v-model="form.lng" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="纬度：">
        <el-input v-model="form.lat" autocomplete="off"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ dict.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否送车上门" prop="ranges">
            <el-radio-group v-model="form.ranges">
              <el-radio
                v-for="dict in shopRangesOption"
                :key="dict.dictValue"
                :label="parseInt(dict.dictValue)"
              >{{ dict.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="服务热线" prop="serviceTel">
            <el-input v-model="form.serviceTel" placeholder="请输入服务热线"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="门店电话" prop="shopTel">
            <el-input v-model="form.shopTel" placeholder="请输入门店电话"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="营业时间段" prop="businessHours">
            <el-row>
              <el-col :span="11">
                <el-time-select
                  style="width: 100%"
                  :key="timeSlot[0]"
                  placeholder="起始时间"
                  v-model="timeSlot[0]"
                  value-format="H:mm:ss"
                  :picker-options="{
                  start: '00:00',
                  step: '00:15',
                  end: '23:45',
                  maxTime:timeSlot[1]
                }">
                </el-time-select>
              </el-col>
              <el-col :span="1" :offset="1">
                至
              </el-col>
              <el-col :span="11">
                <el-time-select
                  style="width: 100%"
                  :key="timeSlot[1]"
                  placeholder="结束时间"
                  v-model="timeSlot[1]"
                  value-format="H:mm:ss"
                  :picker-options="{
                  start: '00:00',
                  step: '00:15',
                  end: '23:45',
                  minTime: timeSlot[0]
                }">
                </el-time-select>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="门店照片" prop="vehicleImageUrl">
        <div class="text-center">
          <shopImg ref="shopImg"/>
        </div>
      </el-form-item>

      <el-input v-show="false" v-model="form.pic"></el-input>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {getCityList} from "@/api/option";
import shopImg from "./shopImg.vue";
import {addStores, putStores} from "@/api/merchant/stores"
import {listData} from "@/api/system/dict/data";

var search = new TMap.service.Suggestion({
  // 新建一个关键字输入提示类
  pageSize: 10, // 返回结果每页条目数
  regionFix: true, // 搜索无结果时是否固定在当前城市
});

export default {
  name: "addStore",
  components: {shopImg},
  props:['statusOptions','shopRangesOption'],
  data() {
    return {
      title: '新增门店',
      dialogVisible: false,
      shop_status: [],
      shop_ranges: [],
      mapflag: true,
      map: undefined,
      mk: undefined,
      citydata: [],
      rules: {
        name: [
          {required: true, message: "店铺名称不能为空", trigger: "blur"}
        ]
      },
      timeSlot: ['00:00', '00:00'],
      statusOptions: [{
        value: '营业',
        label: 1
      }, {
        value: '关闭',
        label: 0
      }],
      form: {
        areaCity: '',
        businessHours: '',
        shopTel: '',
        linkman: '',
        ranges: '',
        status: '',
        serviceTel: ''
      }
    }
  }, methods: {
    // 8-1、地址搜索
    querySearchAsync(str, cb) {
      // 根据状态码
      search.getSuggestions({
        keyword: str,
        location: new TMap.LatLng(this.form.lat || 39.910923647957596, this.form.lng || 116.41338729034514)
      })
        .then((result) => {
          cb(result.data)
          console.log(result)
        })
    },
    // 8-2、选择地址
    handleSelect(item) {
      this.form.address = item.address + item.title
      this.form.lng = item.location.lng
      this.form.lat = item.location.lat
      this.mapflag = true
      let location = new TMap.LatLng(item.location.lat, item.location.lng)
      let map = this.map
      this.mk.setGeometries([{
        id:'marker',
        position: location
      }])
      map.easeTo({zoom: 16, rotation: 0, center: location}, {duration: 3000});
    },
    initMap() {
      if (!this.map) {
        this.$nextTick(() => {
          this.center = new TMap.LatLng(39.910923647957596, 116.41338729034514);
          this.map = new TMap.Map(this.$refs["map-container"], {
            center: this.center, //设置地图中心点坐标
            zoom: 16, //设置地图缩放级别
          });
          let map = this.map
          this.mk = new TMap.MultiMarker({
            map,
            styles: {
              "highlight": new TMap.MarkerStyle({
                "src": "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/marker-pink.png"
              })
            },
            geometries: [{
              id: 'marker',
              position: this.center
            },
            ]
          });
          this.$nextTick(() => {
            const editor = new TMap.tools.GeometryEditor({
              map, // 编辑器绑定的地图对象
              overlayList: [{
                overlay: this.mk, // 可编辑图层
                id: "marker",
                selectedStyleId: "highlight"  // 被选中的marker会变为高亮样式
              }],
              actionMode: TMap.tools.constants.EDITOR_ACTION.INTERACT, // 编辑器的工作模式
              activeOverlayId: "marker", // 激活图层
              selectable: true
            });
          })
        })
      }
    },
    init() {
      getCityList({pid: 0}).then(response => {
        this.citydata = response.data;
      });
    },
    submitForm() {
      console.log(this.form)
      this.form.province = this.form.areaCity[0]
      this.form.city = this.form.areaCity[1]
      this.form.area = this.form.areaCity[2]
      this.form.businessHours = `${this.timeSlot[0]}-${this.timeSlot[1]}`
      this.form.pic = this.$refs.shopImg.options.img;
      if (!this.form.id) {
        addStores(this.form).then(res => {
          if (res.code == 200) {
            this.$message({
              message: '门店新增成功',
              type: 'success'
            });
            this.dialogVisible = false
            window.parent.location.reload()
          }
        })
      } else {
        putStores(this.form).then(res => {
          this.$message({
            message: '门店修改成功',
            type: 'success'
          });
          this.dialogVisible = false
        })
      }
    },
    cancel() {
      this.dialogVisible = false
      this.form = {
        areaCity: '',
        timeSlot: ['', ''],
        businessHours: '',
        shopTel: '',
        // linkman: '',
        ranges: '',
        status: '',
        serviceTel: ''

      }
      this.mapflag = false
    },
    open(info) {
      listData({
        dictType: 'shop_status'
      }).then(res => {
        this.statusOptions = res.rows
      })
      listData({
        dictType: 'shop_ranges'
      }).then(res => {
        this.shopRangesOption = res.rows
      })
      if (info) {
        this.form = info
        this.form.areaCity = [info.province, this.form.city, this.form.area]
        if (info.businessHours != null && info.businessHours.indexOf('-') > 0) {
          let time = info.businessHours.split('-')
          // 获取时间段(时间选择必须是时间类型)
          this.$set(this.timeSlot, 0, time[0])
          this.$set(this.timeSlot, 1, time[1])
        } else {
          this.timeSlot = ['', '']
        }
        this.$nextTick(() => {
          // 给图片路径到组件中
          this.$refs.shopImg.options.img = info.pic
        })
        this.title = '修改门店'
      } else {
        this.title = '新增门店'
        this.form = {
          timeSlot: ['', ''],
          areaCity: '',
          businessHours: '',
          shopTel: '',
          linkman: '',
          ranges: '',
          status: '',
          serviceTel: ''
        }
      }
      this.dialogVisible = true
      this.mapflag = true
      this.initMap()
    }
  },
  created() {
    this.init()
  }
}
</script>
<style scoped lang="scss">
.title {
  margin: auto;
}

.address {
  text-align: center;
}
</style>
